package com.sczmgk.hotline_pzh.location;

import android.content.Context;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.Poi;
import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.utils.MyLog;

/**
 * Created by Administrator on 2016/4/21.
 */
public class LocationUtils {
    /**
     * 转换值
     */
    private static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    private static Context context;
    private LocationService locationService;
    private final String TAG = LocationUtils.class.getSimpleName();
    private static LocationUtils instance;
    private boolean isLocationing = false;
    private boolean isLoginout = true;

    public boolean isLoginout() {
        return isLoginout;
    }

    public void setLoginout(boolean loginout) {
        isLoginout = loginout;
    }

    public boolean isLocationing() {
        return isLocationing;
    }

    public void setLocationing(boolean locationing) {
        isLocationing = locationing;
    }

    public static LocationUtils getInstance(Context context) {
        if (instance == null) {
            instance = new LocationUtils(context);
        }
        return instance;
    }
    private LocationUtils(Context context){
        this.context = context;
    }
    private LocationClient locationClient;

    private OnLocationListener locationListener;
    /**
     * 开始定位
     */
    public void startLocation(OnLocationListener locationListener,boolean isLoginout) {
        this.isLoginout = isLoginout;
        isLocationing = true;
        locationService = MyApp.locationService;
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.registerListener(mListener);
        locationService.start();
        this.locationListener = locationListener;


    }

    /**
     * 停止定位
     */
    public void stopLocation() {
        isLocationing = false;
        if(locationService != null){
            locationService.stop();
            locationService.unregisterListener(mListener);
        }
    }


    /**
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                StringBuffer sb = new StringBuffer(256);
                sb.append("time : ");
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */
                sb.append(location.getTime());
                sb.append("\nerror code : ");
                sb.append(location.getLocType());
                sb.append("\nlatitude : ");
                sb.append(location.getLatitude());
                sb.append("\nlontitude : ");
                sb.append(location.getLongitude());
                sb.append("\nradius : ");
                sb.append(location.getRadius());
                sb.append("\nCountryCode : ");
                sb.append(location.getCountryCode());
                sb.append("\nCountry : ");
                sb.append(location.getCountry());
                sb.append("\ncitycode : ");
                sb.append(location.getCityCode());
                sb.append("\ncity : ");
                sb.append(location.getCity());
                sb.append("\nDistrict : ");
                sb.append(location.getDistrict());
                sb.append("\nStreet : ");
                sb.append(location.getStreet());
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\nDescribe: ");
                sb.append(location.getLocationDescribe());
                sb.append("\nDirection(not all devices have value): ");
                sb.append(location.getDirection());
                sb.append("\nPoi: ");
                if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
                    for (int i = 0; i < location.getPoiList().size(); i++) {
                        Poi poi = (Poi) location.getPoiList().get(i);
                        sb.append(poi.getName() + ";");
                    }
                }
                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("\nspeed : ");
                    sb.append(location.getSpeed());// 单位：km/h
                    sb.append("\nsatellite : ");
                    sb.append(location.getSatelliteNumber());
                    sb.append("\nheight : ");
                    sb.append(location.getAltitude());// 单位：米
                    sb.append("\ndescribe : ");
                    sb.append("gps定位成功");
                    callback(location);
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    // 运营商信息
                    sb.append("\noperationers : ");
                    sb.append(location.getOperators());
                    sb.append("\ndescribe : ");
                    sb.append("网络定位成功");
                    callback(location);
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                    callback(location);
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }
                MyLog.d(TAG, "定位回调了： " + sb.toString());

            }
        }

        private void callback(BDLocation location) {
            if(locationListener != null){
                locationListener.onLocationSuccess(location.getLatitude()+"/"+location.getLongitude(),location.getAddrStr());
            }
            if(isLoginout){
                stopLocation();
            }
        }

    };

    public interface OnLocationListener{
        void onLocationSuccess(String coor, String addr);
    }



    /**
     * 百度转火星
     * @param bd_lat
     * @param bd_lon
     */
    public static double[] decrypt(double bd_lat, double bd_lon)
    {
        try{
            double x = bd_lon - 0.0065, y = bd_lat - 0.006;
            double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
            double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
            double gg_lon = z * Math.cos(theta);
            double gg_lat = z * Math.sin(theta);

            return new double[]{gg_lat,gg_lon};
        }catch(Exception ex){
            return new double[]{bd_lat,bd_lon};
        }

    }

    /**
     * 火星转百度
     * @param gg_lat
     * @param gg_lon
     */
    public static double[] encrypt(double gg_lat, double gg_lon)
    {
        try{
            double x = gg_lon, y = gg_lat;
            double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
            double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
            double bd_lon = z * Math.cos(theta) + 0.0065;
            double bd_lat = z * Math.sin(theta) + 0.006;

            return new double[]{bd_lat,bd_lon};
        }catch(Exception ex){
            return new double[]{gg_lat,gg_lon};
        }
    }
}
